package com.example.projects;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.Facebook;


public class Manufacturer extends Fragment {
	private Facebook fb;
	private SharedPreferences mPrefs;
	private String manid;
	private View root;
	private ViewGroup container;
	
	private OnSharedPreferenceChangeListener prefListener;
	
	public static Fragment newInstance(Context context) {
		Manufacturer f = new Manufacturer();	
		
		return f;
	}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup contain, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPrefs = getActivity().getSharedPreferences("", Context.MODE_PRIVATE);
        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        	  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        		  // check if token set and update UI
        		  if(prefs.getString("access_token", null) != null) {
        			  // logged in
        			  loginUpdateUI();
        		  }else {
        			  // logged out
        			  logoutUpdateUI();
        		  }
        		  
        	  }
        };
        mPrefs.registerOnSharedPreferenceChangeListener(prefListener);
        container = contain;
        root = (ViewGroup) inflater.inflate(R.layout.manufacturer, null);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

        fb = ((CPT3004)getActivity().getApplication()).getFacebook();
    	if(fb == null) {
    		// create new facebook
    		fb = new Facebook(((CPT3004)getActivity().getApplication()).getAppID());
    		
    		// prepare facebook for use
        	String access_token = mPrefs.getString("access_token", null);
        	long expires = mPrefs.getLong("access_expires", 0);
        	
        	// reuse old token if possible
        	if (access_token != null) {
    	    	fb.setAccessToken(access_token);
	        	if(expires != 0) {
	        		fb.setAccessExpires(expires);
	        	}
	        	fb.extendAccessTokenIfNeeded(getActivity().getApplicationContext(), null);
        	}
    		// store facebook
    		((CPT3004)getActivity().getApplication()).setFacebook(fb);
    	}
        
        //Read JSON file
        
		String str = "";
		String namestr = "";
		String descriptionstr = "";
		String sustainabilitystr = "";
		String imagestr = "";
		try {
			str = readFile();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			//JSONArray array = new JSONArray(str);
    		JSONObject json_data = new JSONObject(str);
    		manid = json_data.getString("ManufacturerID");
    		namestr = json_data.getString("Name");
    		descriptionstr = json_data.getString("Description");
    		sustainabilitystr = json_data.getString("Sustainability");
    		imagestr = json_data.getString("Logo");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(container.getContext(), "No data exists.", Toast.LENGTH_SHORT).show();
		}
		
        //setContentView(R.layout.manufacturer);
        
    	Button c = (Button) root.findViewById(R.id.mcom);
    	c.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
		    	Intent intent = getActivity().getIntent();
		    	String barcode = intent.getStringExtra(Main.BARCODE);
    	    	AccessDatabase ad = new AccessDatabase(getActivity());
    	    	ad.execute(barcode, getActivity().getFilesDir().getAbsolutePath(), "mcomment");
			}
    	});
    	
    	
    	// get image if necessary otherwise use the old one
	    ImageView image = (ImageView) root.findViewById(R.id.manufacturerimage);
	    getImage gi = new getImage(container.getContext(), image);
	    gi.execute(imagestr);
        
    	
    	
    	EditText et = ((EditText)root.findViewById(R.id.manflagcom));
    	
    	Button f = (Button) root.findViewById(R.id.mflag);
    	
    	Button mclear = (Button) root.findViewById(R.id.manufacturerclear);
    	mclear.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{

		    	EditText editText = (EditText) root.findViewById(R.id.manflagcom);
		    	//set edit box text to empty string
		    	editText.setText("");
			}
    	});
    	
    	
    	if(fb.isSessionValid()) {
    		f.setVisibility(View.VISIBLE);
    		et.setVisibility(View.VISIBLE);
    		mclear.setVisibility(View.VISIBLE);
    		
    	}else{
    		f.setVisibility(View.GONE);
    		et.setVisibility(View.GONE);
    		mclear.setVisibility(View.GONE);
    		
    	}
    	
    	f.setOnClickListener(new OnClickListener(){
    		public void onClick(View v)
    		{
    	    	// get user comment/reason for flagging and post to database
	    		sendComment();
    		}
    	});
    	
        
		TextView manufacturerinfo = (TextView) root.findViewById(R.id.manufacturerinfo);
		manufacturerinfo.setTextSize(30);
		manufacturerinfo.setText(namestr);
        
/*       TextView barcode = (TextView) root.findViewById(R.id.barcode);
        barcode.setTextSize(20);
        barcode.setText(message);*/

        //Change later into button and drop down boxes
        
        
        TextView description = (TextView) root.findViewById(R.id.mandescription);
        description.setTextSize(20);
        description.setText(descriptionstr);

        RatingBar waterrat = (RatingBar) root.findViewById(R.id.ratingmsustainability);
        waterrat.setRating(Float.parseFloat(sustainabilitystr));
     
        return root;

    }
    
    private void logoutUpdateUI(){
    	EditText et = ((EditText)root.findViewById(R.id.manflagcom));
    	et.setVisibility(View.GONE);
    	Button f = (Button)root.findViewById(R.id.mflag);
    	f.setVisibility(View.GONE);
    	Button pclear = (Button)root.findViewById(R.id.manufacturerclear);
    	pclear.setVisibility(View.GONE);
    }
    
    private void sendComment(){
		Intent intent = getActivity().getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
    	EditText l = (EditText)root.findViewById(R.id.manflagcom);
    	String text = l.getText().toString();
    	ManFlagging fl = new ManFlagging(getActivity());
    	Facebook fb = ((CPT3004)getActivity().getApplication()).getFacebook();
    	MyFacebook.setUsernameID((CPT3004)getActivity().getApplication());
    	if (fb.isSessionValid()) {
    		String name = ((CPT3004)getActivity().getApplication()).getFBName();
    		String id = ((CPT3004)getActivity().getApplication()).getFBID();
    		fl.execute(message, text, id, name, manid);
    	}
    }
    
    private void loginUpdateUI(){
    	EditText et = ((EditText)root.findViewById(R.id.manflagcom));
    	et.setVisibility(View.VISIBLE);
    	Button f = (Button)root.findViewById(R.id.mflag);
    	f.setVisibility(View.VISIBLE);
    	Button pclear = (Button)root.findViewById(R.id.manufacturerclear);
    	pclear.setVisibility(View.VISIBLE);
    }

        	
    private String readFile() throws FileNotFoundException, IOException {
		Intent intent = getActivity().getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(container.getContext().getFilesDir().getAbsolutePath()+"/" + message + "manufacturer.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		return str;
	}
    
    @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	mPrefs.unregisterOnSharedPreferenceChangeListener(prefListener);
    }
}
